<template>
    <el-dialog :title="title" v-model="visible" width="480px" :close-on-click-modal="false" @close="emits('close')">
        <el-form ref="formRef"
                 :model="form"
                 :rules="formRules"
                 :label-width="140">
          
            <el-form-item label="姓名:" prop="real_name">
                <el-input v-model="form.real_name" placeholder="请输入姓名"></el-input>
            </el-form-item>
            
            <el-form-item label="手机号:" prop="mobile" >
                <el-input v-model="form.mobile" placeholder="输入手机号"></el-input>
            </el-form-item>
            <el-form-item label="登录密码:" prop="passwd">
                <el-input v-model="form.passwd" placeholder="请输入登录密码"></el-input>
            </el-form-item>
            <el-form-item label="关联归属员工:" prop="user_id">
                <el-select v-model="form.user_id" placeholder="请选择关联归属员工" clearable>
                    <el-option v-for="(item,index) in userList" :key="index" :label="item.real_name" :value="item.id"></el-option>
                    
                </el-select>
            </el-form-item>
           
           
            <el-form-item label="限制服务区域" prop="region_limit_type">
                <el-select v-model="form.region_limit_type" placeholder="请选择限制服务区域">
                    <el-option label="是" value="2"></el-option>
                    <el-option label="否" value="1"></el-option>
                </el-select>
                
            </el-form-item>
            <el-form-item label="服务区域" prop="area_ids"  v-if="form.region_limit_type == '2'">
                <div>
                    <div class="item" style="display: flex;margin-bottom: 10px;" v-for="(item, index) in form.area_id" :key="index">
                        <el-cascader v-model="form.area_id[index]" :props="cascaderProps" placeholder="请选择所在地区" clearable style="width:100%"></el-cascader>
                        <el-button v-if="index == 0" @click="addArea" style="width:90px" type="primary" link>添加行</el-button>
                        <el-button v-else @click="removeArea(index)"  style="width:90px" type="primary" link>删除</el-button>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="赠送商家账号额度" prop="gift_num">
                <el-input v-model="form.gift_num" placeholder="请输入赠送商家账号额度"></el-input>
                
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="emits('close')">取 消</el-button>
                <el-button type="primary" @click="save(formRef)">确 定</el-button>
            </div>
        </template>
        
    </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, watch, computed, nextTick, onMounted} from 'vue'
import { ElMessage } from 'element-plus'

import type { FormInstance, FormRules, CascaderProps } from 'element-plus'

import { getProviderDetail, saveProvider, editProvider } from 'services/setting'

import { getRegion,getUserList } from 'services/system'

import systemStore from '@/store/modules/system'

const $systemStore = systemStore()

const emits = defineEmits(['close', 'success'])

const formRef = ref<FormInstance>()

const form = ref({
    id: undefined,
    mobile: '',
    real_name: '',
    passwd: '',
    user_id: '',
    region_limit_type:  '',
    area_id:[[]],
    gift_num:''
})

const checkPhone = (rule:any,value:any,callback:any) => {
    let reg = /^1[0-9]{10}$/;
    
    if (value === '') {
        callback(new Error('请输入手机号'))
    } else if (!reg.test(value)) {
        callback(new Error('请输入正确的手机号'))
    } else {
        callback()
    }
}

const formRules = reactive<FormRules>({
    account:[{required:true,message:'请输入账号名'},{max:10,message:'最多只能10个文字'}],
    name:[{required:true, message:'请输入姓名'}],
    mobile:[{required:true, validator:checkPhone, trigger:'blur'}],
})

const props = defineProps<{
    dialogVisible:boolean,
    id?:number,
    state:string,
    departTree?:[]
}>();

const visible = ref(false)

const cascaderProps:CascaderProps = {
    lazy:true,
    label:'region_name',
    value:'id',
    lazyLoad(node:any, resolve){
        const { level } = node
        if (level == 0) {
            getRegion({}).then(res => {
                resolve(res.items)
            })
        } else if (level == 1) {
            getRegion({parent_id:node.data.id}).then(res => {
                resolve(res.items)
        
            })
        } else if (level == 2) {
            getRegion({parent_id:node.data.id}).then(res => {
                res.items.forEach((item:any) => {
                    item.leaf = true
                })
                resolve(res.items)
            })
        }
    }
}

const addArea = () => {
    form.value.area_id.push([])
}

const removeArea = (index:any) => {
    form.value.area_id.splice(index, 1)
}

watch(() => props.dialogVisible, async (val) => {
    visible.value = val
    console.log(props.state)
    if (visible.value === true) {
        await nextTick()
        if (props.state == 'edit') {
            if (props.id) {
                getDetail(props.id)
            }
        } else {
            formRef.value?.resetFields()
            form.value.area_id = [[]]
            form.value.id = undefined
        }
        
    }
},{
    immediate:true
})

const title = computed(() => {
    return props.state == 'add' ? '新增账号' : '编辑账号'
})

const save = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            let data = JSON.parse(JSON.stringify(form.value))
            let area_ids = <any>[]

            data.area_id.forEach((item:any) => {
                area_ids.push(item[2])
            })

            data['area_ids'] = area_ids
            if (data.id) {
                editProvider(data).then(res => {
                    ElMessage.success('操作成功')
                    emits('success')
                })
            } else {
                saveProvider(data).then(res => {
                    ElMessage.success('操作成功')
                    emits('success')
                })
            }
           
        } else {
            console.log('error submit', fields)
        }
    }) 
}

const getDetail = (id:number) => {
    getProviderDetail({id}).then((res:any) => {
        let data = res

        let area = <any>[]
        if (res.region_list.length > 0) {
            res.region_list.forEach((item:any) => {
                area.push([
                    item.province_id,
                    item.city_id,
                    item.area_id
                ])
            })

        } else {
            area.push([])
        }
        data['area_id'] = area
        
        data['type'] = data.agent_type
        form.value = res
    })
}


const userList = ref<any[]>([])

const getInfo = () => {
    getUserList().then(res => {
        userList.value = res.items
    })
}

const dict = computed<any>(() => {
    return $systemStore.dict
})

onMounted(() => {
    getInfo()
    // getRoleData()
    // getDepartData()
})
</script>